package com.canaan.business.service.quality.impl;

import java.util.*;

import com.canaan.business.common.enums.quality.QualityValueTypeEnum;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.SecurityUtils;
import com.canaan.common.utils.TableNoUtil;
import com.canaan.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.canaan.business.mapper.quality.QualityItemMapper;
import com.canaan.business.domain.quality.QualityItem;
import com.canaan.business.service.quality.IQualityItemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 质检项Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-02
 */
@Service
public class QualityItemServiceImpl implements IQualityItemService {
    @Resource
    private QualityItemMapper qualityItemMapper;

    /**
     * 查询质检项
     *
     * @param id 质检项主键
     * @return 质检项
     */
    @Override
    public QualityItem selectQualityItemById(Long id) {
        return qualityItemMapper.selectQualityItemById(id);
    }

    /**
     * 查询质检项列表
     *
     * @param qualityItem 质检项
     * @return 质检项
     */
    @Override
    public List<QualityItem> selectQualityItemList(QualityItem qualityItem) {
        return qualityItemMapper.selectQualityItemList(qualityItem);
    }

    /**
     * 新增质检项
     *
     * @param qualityItem 质检项
     * @return 结果
     */
    @Override
    public int insertQualityItem(QualityItem qualityItem) {
        this.checkNameCount(qualityItem.getName(),qualityItem.getId());
        if(StringUtils.isBlank(qualityItem.getNo())){
            qualityItem.setNo(TableNoUtil.getNo(QualityItem.class));
        }
        qualityItem.setCreateBy(SecurityUtils.getUsername());
        qualityItem.setCreateTime(DateUtils.getNowDate());
        return qualityItemMapper.insertQualityItem(qualityItem);
    }

    /**
     * 判断名称是否重复
     *
     * @param name 名称
     * @param id id
     */
    private void checkNameCount(String name, Long id) {
        int nameCount = this.qualityItemMapper.checkNameCount(name,id);
        if (nameCount > 0) {
            throw new ServiceException("存在相同名称的检验项，请修改");
        }
    }

    /**
     * 批量新增质检项
     *
     * @param qualityItemList 质检项列表
     * @return 结果
     */
    @Override
    public int batchInsertQualityItem(List<QualityItem> qualityItemList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (QualityItem qualityItem : qualityItemList){
            if(StringUtils.isBlank(qualityItem.getNo())){
                qualityItem.setNo(TableNoUtil.getNo(QualityItem.class));
            }
            qualityItem.setCreateBy(username);
            qualityItem.setCreateTime(currerTime);
        }
        int insertNum = 0;
        for (int i=0; i<qualityItemList.size();) {
            int endIndex = i+500;
            if (endIndex > qualityItemList.size()) {
                endIndex = qualityItemList.size();
            }
            insertNum = insertNum + qualityItemMapper.batchInsertQualityItem(qualityItemList.subList(i, endIndex));
            i = endIndex;
        }
        return insertNum;
    }

    /**
     * 修改质检项
     *
     * @param qualityItem 质检项
     * @return 结果
     */
    @Override
    public int updateQualityItem(QualityItem qualityItem) {
        this.checkNameCount(qualityItem.getName(),qualityItem.getId());
        qualityItem.setUpdateBy(SecurityUtils.getUsername());
        qualityItem.setUpdateTime(DateUtils.getNowDate());
        return qualityItemMapper.updateQualityItem(qualityItem);
    }

    /**
     * 批量修改质检项
     *
     * @param qualityItemList 质检项列表
     * @return 结果
     */
    @Override
    public int batchUpdateQualityItem(List<QualityItem> qualityItemList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (QualityItem qualityItem : qualityItemList){
            qualityItem.setUpdateBy(username);
            qualityItem.setUpdateTime(currerTime);
        }
        int updateNum = 0;
        for (int i=0; i<qualityItemList.size();) {
            int endIndex = i+500;
            if (endIndex > qualityItemList.size()) {
                endIndex = qualityItemList.size();
            }
            updateNum = updateNum + qualityItemMapper.batchUpdateQualityItem(qualityItemList.subList(i, endIndex));
            i = endIndex;
        }
        return updateNum;
    }

    /**
     * 批量删除质检项
     *
     * @param ids 需要删除的质检项主键集合
     * @return 结果
     */
    @Override
    public int deleteQualityItemByIds(Long[] ids) {
        return qualityItemMapper.deleteQualityItemByIds(ids);
    }

    /**
     * 删除质检项信息
     *
     * @param id 质检项主键
     * @return 结果
     */
    @Override
    public int deleteQualityItemById(Long id) {
        return qualityItemMapper.deleteQualityItemById(id);
    }

    /**
     * 查询质检项
     *
     * @param no 编号
     * @return 质检项
     */
    @Override
    public QualityItem selectQualityItemByNo(String no) {
        return qualityItemMapper.selectQualityItemByNo(no);
    }

    /**
     * 批量删除质检项
     *
     * @param nos 需要删除的编号集合
     * @return 结果
     */
    @Override
    public int deleteQualityItemByNos(String[] nos) {
        return qualityItemMapper.deleteQualityItemByNos(nos);
    }

    /**
     * 删除质检项信息
     *
     * @param no 编号
     * @return 结果
     */
    @Override
    public int deleteQualityItemByNo(String no) {
        return qualityItemMapper.deleteQualityItemByNo(no);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<QualityItem> fileDataList) {
        if (StringUtils.isNull(fileDataList) || fileDataList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<String> fileNames = new ArrayList<>();
        // 查询文档中存在的所有检验项，用于校验名称是否重复
        List<String> allQualityItemNameList = this.qualityItemMapper.selectQualityItemNameList();

        // 循环校验必填以及文档内是否存在重复数据
        for (int i = 0; i < fileDataList.size(); i++) {
            QualityItem fileEntity = fileDataList.get(i);
            int rowNum = i + 2;
            if (StringUtils.isEmpty(fileEntity.getName())) {
                failureNum++;
                failureMsg.append("第" + rowNum + "行主质检项名称不能为空");
                break;
            }
            if (StringUtils.isEmpty(fileEntity.getValueType())) {
                failureNum++;
                failureMsg.append("第" + rowNum + "行值类型不能为空");
                break;
            }else if (StringUtils.isEmpty(QualityValueTypeEnum.getCodeByMessage(fileEntity.getValueType()))){
                failureNum++;
                failureMsg.append("第" + rowNum + "行值类型输入有误");
                break;
            }
            if (fileNames.contains(fileEntity.getName())) {
                failureNum++;
                failureMsg.append("第" + rowNum + "行质检项名称在文档内存在重复数据，请修改");
                break;
            }
            // 校验名称是否已经存在
            if (allQualityItemNameList.contains(fileEntity.getName())) {
                failureNum++;
                failureMsg.append("第" + rowNum + "行主质检项名称 " + fileEntity.getName() + " 在系统中已存在，请修改");
                break;
            }
            // 转换值类型为枚举
            fileEntity.setValueType(QualityValueTypeEnum.getCodeByMessage(fileEntity.getValueType()));
            fileNames.add(fileEntity.getName());
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败！");
            throw new ServiceException(failureMsg.toString());
        } else {
            int addCount = this.batchInsertQualityItem(fileDataList);
            successMsg.insert(0, "导入成功！共新增 " + addCount + " 条数据");
        }
        return successMsg.toString();
    }
}
